package net.gz01.wallet.web.controller.org;

import java.io.File;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jxls.common.Context;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import lombok.extern.slf4j.Slf4j;
import net.gz01.util.ZOExcel;
import net.gz01.util.ZOHttp;
import net.gz01.util.ZOThreadPoolExecutor;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.config.SystemEnum.FilePath;
import net.gz01.wallet.web.config.SystemEnum.OrderStatus;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.OrgUser;
import net.gz01.wallet.web.model.TradeOrder;

@Slf4j
public class TradeOrderController extends BaseController {

	public void search() {
//		OrgUser orgUser = (OrgUser) getSession().getAttribute("loginOrgUser");
//		ZOSearchCondition sc = super.getSearchCondition();
//		Page<TradeOrder> pageResult = TradeOrder.dao.searchForOrg(sc, orgUser.getOrgCode());
//		setAttr("sumMoney", TradeOrder.dao.searchSumMoney(sc));
//		setPageResultToRequest("items", pageResult);
		render("trade/tradeOrderList.html");
	}

	public void listJson() {
		OrgUser orgUser = (OrgUser) getSession().getAttribute("loginOrgUser");
		ZOSearchCondition sc = super.getSearchCondition();
		Page<TradeOrder> pageResult = TradeOrder.dao.searchForOrg(sc, orgUser.getOrgCode());
		renderJson(new PageRespon(pageResult));
	}

	public void report() throws Exception {
		OrgUser orgUser = (OrgUser) getSession().getAttribute("loginOrgUser");
		Map<String, String> orderStatus = new HashMap<>();
		for (OrderStatus os : OrderStatus.values()) {
			orderStatus.put(os.getValue(), os.getName());
		}

		ZOSearchCondition sc = super.getSearchCondition();
		List<TradeOrder> items = TradeOrder.dao.searchReportForOrg(sc, orgUser.getOrgCode());
		String fileName = "交易明细报表";
		Context context = new Context();
		context.putVar("list", items);

		String templatePath = FilePath.ReportTemplate.getValue() + "trade_details.xlsx";
		String targetPath = FilePath.ReportTmp.getValue() + fileName + ".xlsx";
		LinkedHashMap<String, Context> sheetNameAndData = new LinkedHashMap<>();
		sheetNameAndData.put("汇卡交易明细", context);
		String[] templateSheetName = { "sheet1" };
		ZOExcel.exportLargeData(templatePath, targetPath, sheetNameAndData, templateSheetName);
		File file = new File(targetPath);
		renderFile(file);
	}

	public void view() {
		TradeOrder tradeOrder = TradeOrder.dao.findById(getPara("id"));
		setAttr("order", tradeOrder);
		render("trade/tradeOrderView.html");
	}

	/**
	 * 推送
	 */
	public void push() {
		String[] ids = getParaValues("ids");
		ZOThreadPoolExecutor.execute(new Runnable() {
			@Override
			public void run() {
				for (String id : ids) {
					try {
						String result = ZOHttp
								.postString(SystemConfig.config.get("trade_system_url") + "/notify/adminPush", id);
						log.info("商户补发通知结果 <-" + result);
					} catch (Exception e) {
						log.error("商户补发通知异常", e);
					}
				}
			}
		});
		renderSuccess("补发通知成功", false);
	}


	public void charts() {
		OrgUser orgUser = (OrgUser) getSession().getAttribute("loginOrgUser");
		String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		// select substring(createTime,12,2),count(*),sum(amount) from trade_order group by substring(createTime,12,2) order by substring(createTime,12,2)
		String sql = "select count(*) as count, sum(amount) as total from trade_order where orgCode=? and createTime like ?";
		//String sql = "select sum(amount) from trade_order where merchCode=? and createTime like ?";
		List<Record> records = new ArrayList<>();
		DecimalFormat df = new DecimalFormat("00");
		for (int i = 0; i < 24; i++) {
			Record record = Db.findFirst(sql, orgUser.getOrgCode(), date +" "+df.format(i)+"%");
			if (record.getInt("total") == null) {
				record.set("total", 0);
			}else {
				record.set("total", record.getInt("total")/100);			// 分转元，图表展示不需要百分百精确
			}
			records.add(record);
		}
		renderJson(records);
	}
}
